package cn.shop.gameapi.controller;

import cn.hutool.core.util.StrUtil;
import cn.shop.gameapi.model.GameNpc;
import cn.shop.gameapi.model.GatewaySecret;
import cn.shop.gameapi.model.MerchantGamePartition;
import cn.shop.gameapi.model.MerchantGameTemplate;
import cn.shop.gameapi.util.IpUtil;
import cn.shop.gameapi.util.ResponseInfo;
import cn.shop.utils.Putif;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.shop.gameapi.model.SqlContent.*;

/**
 * @author : 李一涵
 * @date : Created in 2021-12-8 17:47
 * @description :
 */
@RestController
@RequestMapping("/{uid}/partition")
public class GamePartitionController {

    private static final Logger LOG = LoggerFactory.getLogger(GamePartitionController.class);

    @Resource
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/list/{templateId}")
    public ResponseInfo<List<Map<String, Object>>> allPartitionByIp(@PathVariable long uid, @PathVariable long templateId, HttpServletRequest request) {
        String ip = IpUtil.getClientIp(request);
        String secret = request.getHeader("secret");
        GatewaySecret gs = null;
        try {
            gs = jdbcTemplate.queryForObject(SELECT_SECRET_IP, new BeanPropertyRowMapper<>(GatewaySecret.class), ip);
        } catch (EmptyResultDataAccessException ignored) {}
        LOG.info("收到的秘钥{}，查到的秘钥{}", secret, gs != null ? gs.getSecret() : "");
        if (gs == null || StrUtil.isBlank(secret) || !StrUtil.equals(gs.getSecret(), secret)) {
            return ResponseInfo.failed("");
        }
        LOG.info("收到的查询分区列表的请求： {} {}", templateId, gs);
        List<MerchantGamePartition> partitions = jdbcTemplate.query(SELECT_PARTITION_T_P,
                new BeanPropertyRowMapper<>(MerchantGamePartition.class), templateId, gs.getIp(), uid);

        for (MerchantGamePartition partition : partitions) {
            List<GameNpc> npcs = jdbcTemplate.query(SELECT_NPC, new BeanPropertyRowMapper<>(GameNpc.class), partition.getId());
            partition.setNpcs(npcs);
        }


        return ResponseInfo.ok(partitions.stream().map(p ->
                Putif.start()
                        .anyway("id", p.getId())
                        .anyway("templateId", p.getTemplateId())
                        .anyway("name", p.getName())
                        .anyway("serverFolder", p.getServerFolder())
                        .anyway("npcs", p.getNpcs())
                        .anyway("createScript", p.getCreateScript())
                        .anyway("alias", p.getAlias())
                        .get())
                .collect(Collectors.toList()));
    }

    @GetMapping("/one/{id}")
    public ResponseInfo<Map<String, Object>> getTemplate(@PathVariable long uid, @PathVariable long id,HttpServletRequest request) {
        String ip = IpUtil.getClientIp(request);
        String secret = request.getHeader("secret");
        GatewaySecret gs = null;
        try {
            gs = jdbcTemplate.queryForObject(SELECT_SECRET_IP, new BeanPropertyRowMapper<>(GatewaySecret.class), ip);
        } catch (EmptyResultDataAccessException ignored) {}
        if (gs == null || StrUtil.isBlank(secret) || !StrUtil.equals(gs.getSecret(), secret)) {
            return ResponseInfo.failed("");
        }

        MerchantGameTemplate t = null;
        try {
            t = jdbcTemplate.queryForObject(SELECT_TEMPLATE_UID_ID,
                    new BeanPropertyRowMapper<>(MerchantGameTemplate.class), uid, id);
        } catch (Exception ignored) {}
        if (t != null) {
            return ResponseInfo.ok(Putif.start()
                    .anyway("id", t.getId())
                    .anyway("name", t.getName())
                    .anyway("ratio", t.getRate())
                    .anyway("charge", t.getCharge())
                    .anyway("currency", t.getGameCurrency())
                    .anyway("multiple", t.getMultiple())
                    .anyway("browserCommand", t.getBrowserCommand())
                    .get());
        }
        return ResponseInfo.ok();
    }

}
